package c10k

import (
	"fmt"
	"strconv"
	"sync"
	"sync/atomic"
	time2 "time"
)

type client struct {
	from     string
	method   string
	request  string
	response string
}

type server struct {
	ip    string
	cliCh chan *client
	done  bool
}

// todo 1.如何处理大量的IO请求
// todo 2.针对从网卡到内核态再到用户态的数据优化
func mockC10k() {
	start := time2.Now()
	var wg sync.WaitGroup
	wg.Add(10000)
	svr := &server{
		ip:    "127.0.0.1",
		done:  false,
		cliCh: make(chan *client, 10000),
	}

	go svr.service(&wg)

	for i := 0; i < 10000; i++ {
		cli := &client{
			from:    "127.0.0." + strconv.Itoa(i),
			method:  "GET",
			request: "header",
		}
		go cli.access(svr)
	}

	wg.Wait()
	cost := time2.Since(start)
	fmt.Println("cost:", cost)
}

func (cli *client) access(svr *server) {
	svr.cliCh <- cli
}

// 每秒钟处理c10k个io请求
func (svr *server) service(wg *sync.WaitGroup) {
	//ticker := time.NewTicker(1 * time.Nanosecond)
	var i int64 = 0
	//for range ticker.C {
	for {
		select {
		case cli := <-svr.cliCh:
			go svr.handle(cli, &i, wg)
		default:
		}
	}
}

func (svr *server) handle(cli *client, i *int64, wg *sync.WaitGroup) {
	atomic.AddInt64(i, 1)
	cli.response = fmt.Sprintf("ack:%d", *i)
	fmt.Println("client: ", cli)
	wg.Done()
}
